<template>
  <div class="app-container">

    <div class="flex jc-between">
      <YxhyTableQuery :query-params.sync="queryParams" :query-columns="queryColumns" @search="handleQuery">
        <template slot="button">
          <el-form-item>
            <el-button v-hasPermi="['config:material:add']" type="success" @click="handleAdd">添加素材</el-button>
            <el-button type="primary" @click="handleBatchDownload">批量下载</el-button>
          </el-form-item>
        </template>
        <template #selectRemote>
          <YxhySelectRemote
            :value.sync="queryParams.create_uid"
            :request-fn="queryUserAllList"
            :request-key="`name_search`"
            :response-id="`id`"
            :response-name="`chinese_name`"
            :placeholder="`请选择创建人`"
          />
        </template>
      </YxhyTableQuery>

      <div class="progress-nav">
        <div v-for="itemKey in Object.keys(progressQueue)" :key="itemKey" class="progress-item">
          <p class="font-color font-14 mr-20">ID：{{ itemKey }}</p>
          <el-progress :percentage="progressQueue[itemKey]" />
        </div>
      </div>
    </div>

    <YxhyTableData
      ref="yxhyTableDataRef"
      :columns="columns"
      :data="tableList"
      :loading="loading"
      @selectionChange="handleRowChange"
    >
      <!-- 视频插槽 -->
      <template #material_url>
        <el-table-column label="视频" align="center" width="auto">
          <template slot-scope="{ row }">
            <template v-if="row.material_url">
              <video :key="`${videoKey}_${row.id}`" width="130" height="140" controls="controls">
                <source :src="row.material_url" type="video/mp4">
              </video>
            </template>
          </template>
        </el-table-column>
      </template>
      <!-- 插槽内容 -->
      <template #action>
        <el-table-column label="操作" width="80" align="center">
          <template slot-scope="scope">
            <div class="table-action-panel">
              <el-button type="success" size="mini" @click="handleDownload(scope.row)">下载</el-button>
              <el-button type="primary" size="mini" @click="handleBrowse(scope.row)">浏览</el-button>
              <el-button v-hasPermi="['config:material:delete']" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </template>
    </YxhyTableData>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryPage.pageNum"
      :limit.sync="queryPage.limit"
      @pagination="init"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="素材名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入素材名称" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <YxhySelect :value.sync="form.type" :columns="typeColumns" />
        </el-form-item>
        <el-form-item label="上传视频" prop="oss_id">
          <MaterialUploadBatchOss
            ref="materialUploadBatchOssRef"
            :video_folder="`material`"
            @uploadLoading="uploadLoading"
            @successResult="successResult"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { columnsStatic } from './Ds.js'
import { deepClone } from '@/utils'
import { queryMaterialLibrary, addMaterialLibrary, MATERIAL_TYPE, deleteMaterialLibrary } from '@/api/config/material'
import axios from 'axios'
import MaterialUploadBatchOss from './components/MaterialUploadBatchOss/index.vue'
import { queryUserAllList } from '@/api/system/account'

export default {
  name: 'MaterialList',
  components: {
    MaterialUploadBatchOss
  },
  data() {
    return {
      // 总条数
      total: 0,
      // 表格数据
      tableList: [],
      // 分页参数
      queryPage: {
        pageNum: 1,
        limit: 10
      },
      // 查询参数
      queryParams: {
        id: undefined,
        name: undefined,
        create_uid: undefined
      },
      // 查询表单
      queryColumns: [
        {
          label: '',
          placeholder: '请输入素材ID',
          type: 'input',
          param: 'id'
        }, {
          label: '',
          placeholder: '请输入素材名称',
          type: 'input',
          param: 'name'
        }, {
          label: '',
          placeholder: '请选择创建人',
          type: 'selectRemote',
          param: 'create_uid'
        }],

      loading: false,
      // 表格列
      columns: columnsStatic,

      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {
        name: undefined,
        type: 1,
        class_id: 1, // 1-默认素材库 2-曼森素材
        oss_id: undefined
      },
      formDetail: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: '请输入素材名称', trigger: ['blur', 'change'] }
        ],
        type: [
          { required: true, message: '请选择类型', trigger: ['blur', 'change'] }
        ],
        oss_id: [
          { required: true, message: '请上传视频', trigger: ['blur', 'change'] }
        ]
      },
      typeColumns: [
        {
          label: '竖屏视频',
          value: 1
        },
        {
          label: '横屏视频',
          value: 2
        }
      ],
      downingQueue: [], // 下载队列
      progressQueue: {}, // 进度条队列

      videoKey: 1, // 控制video标签刷新展示

      batchOssId: [],
      btnDisable: false,
      batchDownloadArray: [], // 选中的表格行数据

      queryUserAllList
    }
  },
  created() {
    this.init()
  },
  methods: {
    async init() {
      this.loading = true
      const res = await queryMaterialLibrary({
        ...this.queryPage,
        ...this.queryParams,
        class_id: 1 // 1-默认素材库 2-曼森素材
      })
      res.data.forEach(e => {
        const { type } = e
        e.type_text = MATERIAL_TYPE[type]

        this.videoKey++
      })
      this.tableList = res.data
      this.total = res.total
      this.loading = false
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        name: undefined,
        type: 1,
        class_id: 1, // 1-默认素材库 2-曼森素材
        oss_id: undefined
      }
      this.resetForm('formRef')
    },
    // 表格多选
    handleRowChange(rows) {
      this.batchDownloadArray = rows
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryPage.pageNum = 1
      this.init()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加素材库'

      this.$nextTick(() => {
        this.$refs.materialUploadBatchOssRef.reset()
      })
    },
    /** 批量下载按钮 */
    handleBatchDownload() {
      if (this.batchDownloadArray.length === 0) return this.$modal.msgError('请先勾选表格数据')

      this.batchDownloadArray.forEach(row => {
        this.handleDownload(row)
      })

      this.batchDownloadArray = []
      this.$refs.yxhyTableDataRef.handleClearSelection()
    },

    uploadLoading() {
      this.btnDisable = true
    },
    // 剧集批量成功上传到OSS，得到数据["视频重命名-ossId","视频重命名-ossId"]
    successResult(ids) {
      this.btnDisable = false
      this.batchOssId = ids
      this.form.oss_id = ids[0]
      console.log(ids)
    },
    // 下载函数
    download(url, name, callback) {
      return new Promise((resolve, reject) => {
        axios(url, {
          method: 'get',
          responseType: 'blob',
          onDownloadProgress: (evt) => {
            if (typeof callback === 'function') {
              const progress = parseInt((evt.loaded / evt.total) * 100)
              console.log('progress: ' + progress + '%')
              callback(progress)
            }
          }
        })
          .then(res => {
            const type = res.headers['content-type'] // 请求头中文件类型
            // 将video/quicktime转换成mov  否则xxx.quicktime下载成功后无法播放
            const newType = type === 'video/quicktime' ? 'mov' : type
            const blob = new Blob([res.data])
            const a = document.createElement('a')
            a.download = name + '.' + newType?.replace('video/', '')
            a.href = URL.createObjectURL(blob)
            a.click()
            URL.revokeObjectURL(a.href)
            a.remove()
            resolve()
          })
          .catch(err => {
            reject(err)
          })
      })
    },
    /** 浏览按钮 */
    handleBrowse(row) {
      const { material_url } = row
      window.open(material_url)
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const { id } = row
      this.$modal
        .confirm('确认删除吗？')
        .then(function() {
          return deleteMaterialLibrary({
            id
          })
        })
        .then(() => {
          this.init()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 下载按钮 */
    handleDownload(row) {
      const { material_url, name, id } = row
      const newName = `${id}_${name}`

      const hasDowning = this.downingQueue.some(downingId => downingId === id)
      if (hasDowning) return this.$modal.msgWarning('视频正在下载中，请勿重复下载')

      // 因为访问地址是https  要将文件的http替换成https，避免发生浏览器阻止请求
      // const material_url_https = material_url.replace('http', 'https')
      const material_url_https = material_url
      const fileType = material_url.substr(-3)

      // this.$modal.msgSuccess(`${newName}.${fileType}开始下载`)
      this.progressQueue[id] = 0
      this.downingQueue.push(id)

      this.download(material_url_https, newName, (progress) => {
        this.progressQueue[id] = progress
        this.$forceUpdate()
      }).then(() => {
        const findIndex = this.downingQueue.findIndex(downingId => downingId === id)
        // 下载成功，移除下载队列
        this.downingQueue.splice(findIndex, 1)
        delete this.progressQueue[id]
        this.$forceUpdate()

        this.$modal.msgSuccess(`${newName}.${fileType}下载成功`)
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          this.batchOssId.forEach((id, index) => {
            this.submitRequest(id, index)
          })
        }
      })
    },
    submitRequest(id, index) {
      const isSuccess = index === this.batchOssId.length - 1
      this.form.oss_id = id

      addMaterialLibrary(this.form).then(res => {
        if (isSuccess) {
          this.$modal.msgSuccess('添加成功')
          this.open = false
          this.init()
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.component-upload-image {
  ::v-deep .el-upload--picture-card {
    width: 200px;
    height: 100px;
    line-height: 100px;
  }

  ::v-deep .el-upload-list--picture-card .el-upload-list__item{
    width: auto;
    height: 100px;
  }
}

.progress-nav {
  margin-left: auto;
  display: flex;
  flex-direction: column;
  .progress-item {
    width: 300px;
    display: flex;
    align-items: center;
  }
  ::v-deep .el-progress {
    flex: 1;
  }
}
</style>
